package com.cangheng.app.init;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

import com.cangheng.app.util.PropsUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/** 
 * @ClassName: InitHelper 
 * @Description: TODO(初始化) 
 * @author grc 
 * @date 2016年4月18日 下午6:40:43 
 * @version 1.0 
 */
public class InitHelper {

	private SessionFactory sessionFactory = null;
	private DataSource dataSource = null;
	private Properties props = null;
	
	public InitHelper(){
		readProps();
		initDataSource();
		initSessionFactory();
//		sessionFactoryTest();
	}
	
	private void sessionFactoryTest(){
		//org.springframework.orm.hibernate4.HibernateTransactionManager
		
		HibernateTransactionManager htm = new HibernateTransactionManager();
		htm.setSessionFactory(this.sessionFactory);
		this.sessionFactory.getCurrentSession();
	}
	
	private void readProps() {
		this.props = PropsUtil.loadProps("default_hibernate");
	}
	
	private void initSessionFactory() {
		LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
		localSessionFactoryBean.setDataSource(this.dataSource);
		localSessionFactoryBean.setHibernateProperties(this.props);
		localSessionFactoryBean.setPackagesToScan("");
		try {
			localSessionFactoryBean.afterPropertiesSet();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		sessionFactory.setMappingResources(mappingResources);
		
		this.sessionFactory = localSessionFactoryBean.getObject();
	}
	
	private void initDataSource(){
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setProperties(this.props);
		this.dataSource = dataSource;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}

}
